import { defineStore } from "pinia";
import { ref } from "vue";

import { getCarList } from "@/api/car";


const useCarStore = defineStore("carStore", () => {
    // 购物车列表
    const list = ref([])
    // 已选列表
    const selectedIds = ref([])
    //是否全选
    const isAllSelected = ref(false)
    // 选中项总金额
    let totalPrice = ref('0.00')

    function setList(data) {
        list.value = data
    }
    function setSelectedIds(data) {
        selectedIds.value = data
    }
    function setIsAllSelected(data) {
        isAllSelected.value = data
    }
    function setTotalPrice(data) {
        totalPrice.value = data
    }
    // 获取购物车列表
    async function getList() {
        const list = await getCarList();
        list.forEach(it => {
            let str = "";
            const obj = JSON.parse(it.spData);
            Object.keys(obj).forEach(key => {
                str += key + "：" + obj[key] + " ";
            });
            it.spDataValue = str;
        });
        list.value = list;
    }
    // 清空购物车
    function clearCar() {
        list.value = [];
        selectedIds.value = [];
        isAllSelected.value = false;
        totalPrice.value = '0.00'
    }

    return {
        list,
        selectedIds,
        isAllSelected,
        totalPrice,
        setList,
        setSelectedIds,
        setIsAllSelected,
        setTotalPrice,
        clearCar,
        getList
    }
}, {
    persist: true
});

export default useCarStore